package com.gigi.datageniebackendmaster.exception;

import cn.hutool.core.util.StrUtil;
import com.gigi.datageniebackendmaster.common.BaseResponse;
import com.gigi.datageniebackendmaster.model.enums.ErrorCodeEnum;
import com.gigi.datageniebackendmaster.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.concurrent.RejectedExecutionException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 *
 * @author Gigi
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 业务异常处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return ResultUtil.error(e.getCode(), e.getMessage());
    }

    /**
     * 运行时异常处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return ResultUtil.error(ErrorCodeEnum.SYSTEM_ERROR);
    }

    /**
     * 参数校验异常处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> bindExceptionHandler(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException：", e);
        List<String> fieldErrors =
                e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        return ResultUtil.error(ErrorCodeEnum.PARAMS_ERROR, StrUtil.join(StrUtil.COMMA, fieldErrors));
    }

    /**
     * 线程池拒绝策略异常处理器
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RejectedExecutionException.class)
    public BaseResponse<?> rejectedExecutionExceptionHandler(RejectedExecutionException e) {
        log.error("RejectedExecutionException", e);
        return ResultUtil.error(ErrorCodeEnum.SYSTEM_BUSY_ERROR);
    }

}
